﻿namespace YK.Console.Business.UserInfos;

internal class UserInfoPageHandler(IReadRepository<UserInfo> _repo) : IRequestHandler<UserInfoPageRequest, PaginationResponse<UserInfoOutput>>
{
    public Task<PaginationResponse<UserInfoOutput>> Handle(UserInfoPageRequest request, CancellationToken cancellationToken)
        => _repo.SimplePageAsync<UserInfoOutput>(request, cancellationToken: cancellationToken);
}

internal class ChangePasswordHandler(IRepository<UserInfo> repo) : IRequestHandler<ChangePasswordRequest, Guid>
{
    private readonly IRepository<UserInfo> _repo = repo;

    public async Task<Guid> Handle(ChangePasswordRequest request, CancellationToken cancellationToken)
    {
        var userInfo = await _repo.GetByIdAsync(request.UserId, cancellationToken) ?? throw ResultOutput.Exception("用户不存在");
        userInfo.EncryptPassword(request.Password);
        await _repo.UpdateAsync(userInfo);
        return userInfo.Id;
    }
}

internal class UploadAvatarHandler : IRequestHandler<UploadAvatarRequest, Guid>
{
    public Task<Guid> Handle(UploadAvatarRequest request, CancellationToken cancellationToken)
    {
        throw new NotImplementedException();
    }
}

internal class UpdateUserInfoHandler(IRepository<UserInfo> repo) : IRequestHandler<UpdateUserInfoRequest, Guid>
{
    private readonly IRepository<UserInfo> _repo = repo;

    public async Task<Guid> Handle(UpdateUserInfoRequest request, CancellationToken cancellationToken)
    {
        var userInfo = await _repo.GetByIdAsync(request.Id, cancellationToken) ?? throw ResultOutput.Exception("用户不存在");
        userInfo.Update(account: request.Account,  nickName: request.NickName,
              mobile: request.Mobile, email: request.Email);
        await _repo.UpdateAsync(userInfo, cancellationToken);
        return userInfo.Id;
    }
}

/// <summary>
/// 创建普通用户
/// </summary>
/// <param name="repo"></param>
internal class CreateUserInfoHandler(IRepository<UserInfo> repo) : IRequestHandler<CreateUserInfoRequest, Guid>
{
    private readonly IRepository<UserInfo> _repo = repo;

    public async Task<Guid> Handle(CreateUserInfoRequest request, CancellationToken cancellationToken)
    {
        var userInfo = request.Adapt<UserInfo>();
        var appOptions = AppCore.GetConfig<AppOptions>();
        userInfo.PasswordEncryptType = appOptions.PasswordEncryptType;
        var pwd = request.Password.IsNullOrEmpty()
            ? appOptions.DefaultPassword
            : request?.Password ?? string.Empty;
        userInfo.EncryptPassword(pwd);
        await _repo.AddAsync(userInfo, cancellationToken);
        return userInfo.Id;
    }
}
